package com.jackstraw.jack_base.routing.openfeign.config;


import com.jackstraw.jack_base.util.ObjectUtil;
import com.jackstraw.jack_base.util.StringUtil;
import com.jackstraw.jack_base.util.tenant.contextholder.TenantContextHolder;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;


/**
 * 设置Feign请求前拦截器
 */
@Slf4j
@Configuration
@EnableFeignClients
public class OpenFeignConfiguration {

    @Bean
    @Primary
    public RequestInterceptor requestInterceptor() {
        RequestInterceptor requestInterceptor = requestTemplate -> {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (ObjectUtil.ObjectUtilByLang3.isEmpty(servletRequestAttributes)
                    || ObjectUtil.ObjectUtilByLang3.isEmpty(servletRequestAttributes.getRequest())) {
                //设置租户
                String tenantName = TenantContextHolder.get();
                requestTemplate.header("tenantName", tenantName);
            } else {
                HttpServletRequest request = servletRequestAttributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (ObjectUtil.ObjectUtilByLang3.isNotEmpty(headerNames)) {
                    while (headerNames.hasMoreElements()) {
                        String headerName = headerNames.nextElement();
                        String headerValue = request.getHeader(headerName);
                        requestTemplate.header(headerName, headerValue);
                    }
                }
                String tenantName = request.getParameter("tenantName");
                if (StringUtil.StringUtilsBylang3.isNotEmpty(tenantName)) {
                    requestTemplate.header("tenantName", tenantName);
                }
            }
        };
        return requestInterceptor;
    }

}
